#
# Package.
#

package iSOCK::Controller::Admin::Sessions;

#
# Dependencies.
#

use DateTime;
use Try::Tiny;

#
# Parent.
#

use Moose;
use namespace::autoclean;

BEGIN { extends 'iSOCK::Controller::Root' }

#
# Documentation.
#

=head1 NAME

iSOCK::Controller::Admin::Sessions - Controller for iSOCK

=head1 DESCRIPTION

[enter your description here]

=head1 METHODS

=cut

#
# Subs.
#

sub index :Path :Args(0) {
  my ( $self, $c ) = @_;

  $self->check_user_authorization ( $c, 'can_bofh' );
  
  my $tmp = $c->config->{directory}->{tmp};
  
  my $parameters = $c->request->parameters;

  if ( $c->request->method eq 'POST' && $parameters->{form_sessions_reap} ) {
    my @ids = grep { m/^[0-9a-f]{40}$/ } sort keys %$parameters;
    
    for my $id ( @ids ) {
      if ( my $user_r = $c->model ( 'App::User' )->search ({ session_id => $id })->first ) {
        $c->stash->{action_failed} .= "Session $id belongs to " . $user_r->name . "! ";
      }
      else {
        try {
          system "rm -rf $tmp/$id";
          
          if ( my $session_r = $c->model ( 'App::Session' )->find ( $id ) ) {
            $session_r->delete;
          }
        }
        catch {
          ( my $why = $_ ) =~ s/ at \/.+\.$//;

          $c->stash->{action_failed} .= $why;
        };
      }
    }
    
    unless ( $c->stash->{action_failed} ) {
      my $count = scalar @ids;

      $c->stash->{action_succeeded} = "Reaped $count session" . ( $count >  1 ? "s." : "." );
    }
  }
    
  if ( $parameters->{auto_refresh} ) {
    $c->stash ( auto_refresh => 1 );
  }
  
  $c->stash (
    user_rs  => $c->model ( 'App::User' ),
    sessions => $c->model ( 'App' )->sessions_loh ( $tmp ),
  );

  $c->forward ( qw( iSOCK::Controller::Root render_view ) );
}

#
# Documentation.
#

=head1 AUTHOR

Xavier Caron

=head1 LICENSE

This library is free software, you can redistribute it and/or modify
it under the same terms as Perl itself.

=cut

#
# True.
#

1;
